// This file is managed by Git and reads data from public/demos.json
// Last updated: 2025-08-21

// 从public/demos.json获取演示数据
let demos = [];
let loadPromise = null;

/**
 * 异步加载demos.json数据
 * 该函数从服务器获取演示数据并赋值给 demos 变量
 */
function loadDemosData() {
  if (loadPromise) {
    return loadPromise; // 避免重复加载
  }

  loadPromise = new Promise((resolve, reject) => {
    fetch('/demos.json')
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
      })
      .then(demosJson => {
        if (!demosJson || !Array.isArray(demosJson.demos)) {
          throw new Error('Invalid data format in demos.json');
        }
        demos = demosJson.demos;
        resolve(demos);
      })
      .catch(error => {
        console.error('Failed to load demos.json:', error);
        demos = [];
        reject(error);
      });
  });

  return loadPromise;
}

// 初始化加载数据
loadDemosData();

// Group demos by category
const demosByCategory = {};

export function getDemos() {
  // 返回Promise确保调用者可以等待数据加载完成
  return loadDemosData();
}

export function getDemosByCategory() {
  // 只有在数据加载完成后才进行分组
  if (demos.length > 0 && Object.keys(demosByCategory).length === 0) {
    demos.reduce((acc, demo) => {
      if (!acc[demo.category]) {
        acc[demo.category] = [];
      }
      acc[demo.category].push(demo);
      return acc;
    }, demosByCategory);
  }
  return demosByCategory;
}

export default demos;